package org.zoomdev.zoom.protobuf.modules;

import io.protostuff.*;
import org.zoomdev.zoom.common.utils.Creators;

import java.io.IOException;
import java.util.Collection;

public final class ProtostuffUtils {


    public static byte[] serialize(Schema schema, Object data) {
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        return ProtostuffIOUtil.toByteArray(data, schema, buffer);
    }

    public static <T> T deserialize(Schema<T> schema, byte[] src) {
        T data = schema.newMessage();
        ProtostuffIOUtil.mergeFrom(src, data, schema);
        return data;
    }

    public static byte[] serializeList(Schema schema, Iterable list) {
        try {
            LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
            ProtostuffOutput output = new ProtostuffOutput(buffer);
            for (Object data : list) {
                if (data != null) {
                    output.writeObject(1, data, schema, true);
                }
            }
            return output.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static Object deserializeList(Class<?> type, Schema schema, byte[] bytes) {
        try {
            Collection list = Creators.newCollection(type);
            ByteArrayInput input = new ByteArrayInput(bytes, 0, bytes.length, true);
            for (int number = input.readFieldNumber(schema); number != 0; number = input.readFieldNumber(schema)) {
                Object value = input.mergeObject(null, schema);
                list.add(value);
            }
            input.checkLastTagWas(0);
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
